import aiohttp
import asyncio


Config = {"ip": "http://127.0.0.1", "port": 9988}


class HttpClient:
    def __init__(self, config: dict):
        self.config = config
        self.init_data()

    def init_data(self):
        self.address = self.config["ip"]
        self.port = self.config["port"]
        self.base_url = f"{self.address}:{self.port}"

    async def async_loop_run(self):
        session = aiohttp.ClientSession()
        self.event_loop = asyncio.get_running_loop()
        url = self.base_url
        while True:
            try:
                async with session.get(url) as resp:
                    print("Status:", resp.status)
                    print("Content-type:", resp.headers["content-type"])
                    html = await resp.text()
                    print("recv:\n", html)

            except aiohttp.client_exceptions.ClientConnectorError as e:
                print("连接异常, 断开连接")
                break
            except Exception as e:
                print("未知异常, 断开连接", e)
                break
            await asyncio.sleep(1)

        await session.close()


if __name__ == "__main__":
    client = HttpClient(Config)
    asyncio.run(client.async_loop_run())
